<?php
namespace App\Http\Controllers\Business\App\Auth;
use App\Models\SmsMessage;
use App\Models\User;
use App\Models\UnregisteredUser;
use App\Models\DoubleCoupon;
use App\Utils\DeviceTool;
use App\Http\Controllers\Business\App\Salesman\SalesmanManagement;
use Illuminate\Support\Facades\Redis;
use Log;

class AppAuth
{
    //注册或者登录
    public static function registerOrLogin($mobile,$code,$avatar='',$nickname='',$openid='',$type='0',$channel='',$deviceid='',$osversion='',$phonetype='',$versioncode='', $ip='', $localCity='') {
        //ios 测试帐号
        if(env('WEB_URL') == 'https://test2.fbw-china.com/') {
            if(($mobile == '18888888888') && ($code=='777777')){
                return ['status'=>'success','message'=>'登录成功！','data'=>array('userid'=>'10941')];
            }
            if(($mobile == '17777777777') && ($code=='888888')){
                return ['status'=>'success','message'=>'登录成功！','data'=>array('userid'=>'248352')];
            }
        } else {
            if($mobile == '18888888888'){
                return ['status'=>'success','message'=>'登录成功！','data'=>array('userid'=>'10941')];
            }
        }
        if(!$mobile || !$code) {
            return ['status'=>'failed','message'=>'请求数据不完整！'];
        }
        if(!SmsMessage::loginIdentifyingCodeVerify($mobile,$code,'1')) {
            return ['status'=>'failed','message'=>'验证码错误！'];
        }
        $olduser = User::where('mobile', $mobile)->select('id','status')->first();
        if($olduser) {
            //登录
            $status = $olduser['status'];
            if($status == '0') {
                return ['status'=>'failed', 'message'=>'你帐号已被禁用，请联系客服'];
            }
            $userid = $olduser['id'];
            $user = User::find($userid);
            $user->logintime=date('Y-m-d H:i:s',time());
            if($openid && $type == '1') {
                $user->wxopenid=$openid;
            } elseif($openid && $type == '2') {
                $user->qqopenid=$openid;
            } elseif($openid && $type == '3') {
                $user->wbopenid=$openid;
            } else {
                if($openid){
                    $user->openid=$openid;
                }
            }
            if($ip && ($user->registerarea == '')) {
                $cityResult = DeviceTool::getCityByIp($ip);
                if($cityResult['status'] == 'failed') {
                    $cityName = '';
                } else {
                    $cityName = $cityResult['data']['city'];
                }
                $user->registerarea = $cityName;
            }
            $user->save();
            return ['status'=>'success','message'=>'登录成功！','data'=>array('userid'=>$userid)];
        } else {
            //注册
            $user = new User;
            $user->mobile = $mobile;
            $user->avatar = $avatar ? $avatar : env('IMAGE_DOMAIN') . '/images/default_avatar.png';
            if($nickname == '') {
                $nickname = "fbw_" . date('ymdhis');
            }
            $user->nickname = $nickname;
            $user->logintime = date('Y-m-d H:i:s',time());
            if($openid && $type == '1') {
                $user->wxopenid=$openid;
            } elseif($openid && $type == '2') {
                $user->qqopenid=$openid;
            } elseif($openid && $type == '3') {
                $user->wbopenid=$openid;
            } else {
                $user->openid=$openid;
            }
            $user->status = '1';
            $cityName = '';
            if($ip) {
                $cityResult = DeviceTool::getCityByIp($ip);
                if ($cityResult['status'] == 'success') {
                    $cityName = $cityResult['data']['city'];
                    if($cityName == 'Array') {
                        $cityName = '';
                    }
                }
                $user->registerarea = $cityName;
            }
            if($deviceid && $phonetype && $channel) {
                $user->deviceid = $deviceid;
                $addShopSalesmanResult = SalesmanManagement::addSalesmanByRegister($mobile, $deviceid, $cityName, $phonetype, $channel, $localCity);
                if($addShopSalesmanResult['status'] == 'success') {
                    $salesmanType = isset($addShopSalesmanResult['data']['salesmantype'])?$addShopSalesmanResult['data']['salesmantype'] : '';
                    if($salesmanType == 'shopsalesman') {
                        //商家地推
                        $shopId = isset($addShopSalesmanResult['data']['shopid'])?$addShopSalesmanResult['data']['shopid']:'';
                        $user->shopid = $shopId;
                    } elseif($salesmanType == 'usersalesman') {
                        //用户个人地推
                        $salesmanId = isset($addShopSalesmanResult['data']['salesmanid'])?$addShopSalesmanResult['data']['salesmanid']:'';
                        $user->salesmanid = $salesmanId;
                    }
                }
                $user->phonetype = $phonetype;
            }
            if($channel) {
                $user->registersource = $channel;
            }
            if($osversion) {
                $user->osversion = $osversion;
            }
            if($versioncode) {
                $user->versioncode = $versioncode;
            }
            if($ip) {
                $user->ip = $ip;
            }
            $user->save();

            return ['status'=>'success','message'=>'登录成功！','data'=>array('userid'=>$user->id)];
        }
    }
    //版本v15的注册或者登录
    public static function registerOrLoginByV15Version($mobile, $code,$qrCodeUrl='',$avatar='', $nickname='',$openid='',$type='0',$channel='',$deviceId='',$osVersion='',$phoneType='',$versionCode='', $ip='', $localCity='') {
        //ios 测试帐号
        if(env('WEB_URL') == 'https://test2.fbw-china.com/') {
            if(($mobile == '18888888888') && ($code=='777777')){
                return ['status'=>'success','message'=>'登录成功！','data'=>array('userid'=>'10941')];
            }
            if(($mobile == '17777777777') && ($code=='888888')){
                return ['status'=>'success','message'=>'登录成功！','data'=>array('userid'=>'248352')];
            }
        } else {
            if($mobile == '18888888888'){
                return ['status'=>'success','message'=>'登录成功！','data'=>array('userid'=>'10941')];
            }
        }
        if(!$mobile || !$code) {
            return ['status'=>'failed','message'=>'请求数据不完整！'];
        }
        if(!SmsMessage::loginIdentifyingCodeVerify($mobile,$code,'1')) {
            return ['status'=>'failed','message'=>'验证码错误！'];
        }
        $oldUser = User::where('mobile', $mobile)->first();
        if($oldUser) {
            //登录
            $status = $oldUser['status'];
            if($status == '0') {
                return ['status'=>'failed', 'message'=>'你帐号已被禁用，请联系客服'];
            }
            $userId = $oldUser['id'];
            $oldUser->logintime=date('Y-m-d H:i:s');
            if($openid && $type == '1') {
                $oldUser->wxopenid=$openid;
            } elseif($openid && $type == '2') {
                $oldUser->qqopenid=$openid;
            } elseif($openid && $type == '3') {
                $oldUser->wbopenid=$openid;
            } else {
                if($openid){
                    $oldUser->openid=$openid;
                }
            }
            if($ip && ($oldUser->registerarea == '')) {
                $cityResult = DeviceTool::getCityByIp($ip);
                if($cityResult['status'] == 'failed') {
                    $cityName = '';
                } else {
                    $cityName = $cityResult['data']['city'];
                }
                $oldUser->registerarea = $cityName;
            }
            $oldUser->save();
            return ['status'=>'success','data'=>array('userid'=>$userId)];
        } else {
            //注册
            $user = new User;
            $user->mobile = $mobile;
            $user->avatar = $avatar ? $avatar : env('IMAGE_DOMAIN') . '/images/default_avatar.png';
            if($nickname == '') {
                $nickname = "fbw_" . date('ymdhis');
            }
            $user->nickname = $nickname;
            $user->logintime = date('Y-m-d H:i:s',time());
            if($openid && $type == '1') {
                $user->wxopenid=$openid;
            } elseif($openid && $type == '2') {
                $user->qqopenid=$openid;
            } elseif($openid && $type == '3') {
                $user->wbopenid=$openid;
            } else {
                $user->openid=$openid;
            }
            $user->status = '1';
            $cityName = '';
            if($ip) {
                $cityResult = DeviceTool::getCityByIp($ip);
                if ($cityResult['status'] == 'success') {
                    $cityName = $cityResult['data']['city'];
                    if($cityName == 'Array') {
                        $cityName = '';
                    }
                }
                $user->registerarea = $cityName;
            }
            if($deviceId && $phoneType && $channel) {
                $user->deviceid = $deviceId;
                $qrCodeUrl = urldecode($qrCodeUrl);
                $addShopSalesmanResult = SalesmanManagement::addSalesmanByRegisterAndV15Version($mobile, $qrCodeUrl, $deviceId, $phoneType, $channel, $cityName, $localCity);
                if ($addShopSalesmanResult['status'] == 'success') {
                    $salesmanType = isset($addShopSalesmanResult['data']['salesmantype']) ? $addShopSalesmanResult['data']['salesmantype'] : '';
                    if ($salesmanType == 'shopsalesman') {
                        //商家地推
                        $shopId = isset($addShopSalesmanResult['data']['shopid']) ? $addShopSalesmanResult['data']['shopid'] : '';
                        $user->shopid = $shopId;
                    } elseif ($salesmanType == 'usersalesman') {
                        //用户个人地推
                        $salesmanId = isset($addShopSalesmanResult['data']['salesmanid']) ? $addShopSalesmanResult['data']['salesmanid'] : '';
                        $user->salesmanid = $salesmanId;
                    }
                }
                $user->phonetype = $phoneType;
            }
            if($channel) {
                $user->registersource = $channel;
            }
            if($osVersion) {
                $user->osversion = $osVersion;
            }
            if($versionCode) {
                $user->versioncode = $versionCode;
            }
            if($ip) {
                $user->ip = $ip;
            }
            $user->save();

            return ['status'=>'success','message'=>'登录成功！','data'=>array('userid'=>$user->id)];
        }
    }
    //第三方登录
    public static function thirdLogin($openid,$type) {
        if(!$openid || !$type) {
            return ['status'=>'failed','message'=>'请求数据不完整！'];
        }
        $user = '';
        if($openid && $type == '1') {
            $user = User::where('wxopenid',$openid)->select('id', 'status')->first();
        }
        elseif($openid && $type == '2') {
            $user = User::where('qqopenid',$openid)->select('id', 'status')->first();
        }
        elseif($openid && $type == '3') {
            $user = User::where('wbopenid',$openid)->select('id', 'status')->first();
        }
        if($user) {
            $status = $user['status'];
            if($status == '0') {
                return ['status'=>'failed', 'message'=>'该帐号已禁用，请联系客服'];
            }
            $userid = $user['id'];
            return ['status'=>'success','data'=>['isregistered'=>'1', 'userid'=>$userid]];
        } else {
            return ['status'=>'success','data'=>['isregistered'=>'0', 'userid'=>'']];
        }
    }
    //是否第一次登录
    public static function isFirstLogin($mobile) {
        if(!$mobile) {
            return ['status'=>'failed','message'=>'请求的数据不完整！'];
        }
        $userId = User::where('mobile', $mobile)->pluck('id')->first();
        if($userId) {
            return ['status'=>'success','message'=>'该用户非首次登录！', 'data'=>['islogin' => '1']];
        } else {
            return ['status'=>'success', 'data'=>['islogin' => '0']];
        }
    }
    //注册两小时内的扫描二维码绑定商家地推或者个人地推
    public static function batchSalesmanQrCodeAfterTwoHourRegister($userId, $qrCodeUrl, $deviceId, $phoneType, $channel, $ip, $localCity='') {
        if(!$userId||!$qrCodeUrl||!$deviceId||!$phoneType||!$channel||!$ip) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $user = User::where('id', $userId)->first();
        if(!$user) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        //两小时内扫描有效
        if(strtotime($user->created_at) < (time()-2*60*60)) {
            return ['status'=>'failed', 'message'=>'时间已过'];
        }
        if($user->salesmanid || ($user->shopid != 0)) {
            return ['status'=>'failed', 'message'=>'帐号已绑定了信息'];
        }
        $cityName = '';
        $cityResult = DeviceTool::getCityByIp($ip);
        if ($cityResult['status'] == 'success') {
            $cityName = $cityResult['data']['city'];
            if($cityName == 'Array') {
                $cityName = '';
            }
        }
        $salesmanType = '';
        if($qrCodeUrl) {
            $qrCodeUrl = urldecode($qrCodeUrl);
            $addShopSalesmanResult = SalesmanManagement::addSalesmanByRegisterAndV15Version($user->mobile, $qrCodeUrl, $deviceId, $phoneType, $channel, $cityName, $localCity);
            if ($addShopSalesmanResult['status'] == 'success') {
                $salesmanType = isset($addShopSalesmanResult['data']['salesmantype']) ? $addShopSalesmanResult['data']['salesmantype'] : '';
                if ($salesmanType == 'shopsalesman') {
                    //商家地推
                    $shopId = isset($addShopSalesmanResult['data']['shopid']) ? $addShopSalesmanResult['data']['shopid'] : '';
                    $user->shopid = $shopId;
                } elseif ($salesmanType == 'usersalesman') {
                    //用户个人地推
                    $salesmanId = isset($addShopSalesmanResult['data']['salesmanid']) ? $addShopSalesmanResult['data']['salesmanid'] : '';
                    $user->salesmanid = $salesmanId;
                }
            }
        }
        $user->save();
        if($salesmanType == 'usersalesman') {
            return ['status' => 'success', 'message' => '你被邀请成功啦！'];
        } else {
            return ['status' => 'success', 'message' => ''];
        }
    }
    //使地推用户获取翻贝券
    public static function makeRecommendUserGetDoubleCoupon($mobile) {
        if(!$mobile) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $unregisteredUser = UnregisteredUser::where('mobile', $mobile)->orderBy('id', 'desc')->first();
        if(!$unregisteredUser) {
            return ['status'=>'failed', 'message'=>'没有被邀请过'];
        }
        $parentId = $unregisteredUser->parentid;
        $doublecoupon = new DoubleCoupon;
        $doublecoupon->userid = $parentId;
        $doublecoupon->starttime = date('Y-m-d H:i:s',time());
        $time=time()+30*24*3600;
        $endtime=date('Y-m-d',$time);
        $doublecoupon->endtime = $endtime;
        $doublecoupon->status = '0';
        $doublecoupon->type = 'recharge';
        $doublecoupon->save();
        $user = User::find($parentId)->increment('doublecoupons', 1);
        return ['status'=>'success', 'message'=>'获取成功'];
    }
    //发送验证码，type属性：1用户端，2商户端，3后台; mode: 1短信验证码，2语音验证码
    public static function getCode($mobile, $type, $mode){
        //ios 测试帐号
        if ($mobile == "18888888888" || $mobile== "177777777777") {
            return ['status' => 'success', 'message' => '短信发送成功！'];
        }
        if(!$mobile || !$type || !$mode) {
            return ['status'=>'failed','message'=>'请求数据不完整！'];
        }
        $result = SmsMessage::loginIdentifyingCode($mobile,$type, $mode);
        if($result == '1') {
            if($mode == '2') {
                return ['status' => 'success', 'message' => '请留意语音来电'];
            } else {
                return ['status' => 'success', 'message' => '验证码发送成功！'];
            }
        } elseif($result == '2') {
            return ['status' => 'failed', 'message'=>'60秒内只能获取一次验证码，请稍后重试！'];
        } else {
            return ['status'=>'failed','message'=>'验证码发送失败，请稍后再试！'];
        }
    }
    //验证验证码
    public static function validataSmsCode($mobile,$code) {
        if(SmsMessage::loginIdentifyingCodeVerify($mobile,$code,'1') == false) {
            return ['status'=>'failed','message'=>'验证码错误！'];
        } else {
            return ['status'=>'success', 'message'=>'验证码成功'];
        }
    }
    //获取验证码并验证手机是否注册过
    public static function getCodeAndJudgeRegister($mobile, $type, $mode) {
        if(!$mobile||!$type||!$mode) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if(User::where('mobile', $mobile)->get()->count() > 0) {
            return ['status'=>'failed', 'message'=>'该手机已注册过'];
        }
        $result = SmsMessage::loginIdentifyingCode($mobile,$type, $mode);
        if($result == '1') {
            if($mode == '2') {
                return ['status' => 'success', 'message' => '请留意语音来电'];
            } else {
                return ['status' => 'success', 'message' => '验证码发送成功！'];
            }
        } elseif($result == '2') {
            return ['status' => 'failed', 'message'=>'60秒内只能获取一次验证码，请稍后重试！'];
        } else {
            return ['status'=>'failed','message'=>'验证码发送失败，请稍后再试！'];
        }
    }
    //修改用户手机号码
    public static function changeMobile($userid,$oldmobile,$oldcode,$newmobile,$newcode) {
        if(!$userid || !$oldmobile || !$oldcode || !$newmobile || !$newcode) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        $user = User::find($userid);
        if($user) {
            if($user['mobile'] = $oldmobile) {
                if(SmsMessage::loginIdentifyingCodeVerify($oldmobile,$oldcode,'1') && SmsMessage::loginIdentifyingCodeVerify($newmobile,$newcode,'1')) {
                    $user->mobile = $newmobile;
                    $user->save();
                    return ['status'=>'success','message'=>'修改成功！'];
                } else {
                    return ['status'=>'failed','message'=>'验证码错误！'];
                }
            } else {
                return ['status'=>'failed','message'=>'原手机号码不正确！'];
            }
        } else {
            return ['status'=>'failed','message'=>'没有用户信息！'];
        }
    }
    //通过用户id获取用户token
    public static function getToken($userid) {
        if (!$userid) {
            return ['status'=>'failed','message'=>'没有用户信息！'];
        }
        if(User::find($userid)) {
            do{
                $token = self::getRandChar(128);
            } while(Redis::get('ApiToken:' . $token));
            if (Redis::get('ApiToken:UserId:' . $userid)) {
                Redis::del('ApiToken:' . Redis::get('ApiToken:UserId:' . $userid));
            }
            Redis::setex('ApiToken:' . $token, 2592000, $userid);
            Redis::setex('ApiToken:UserId:' . $userid, 2592000, $token);
            //Redis::setex('ApiToken:' . $token, 480, $userid);    //TODO
            //Redis::setex('ApiToken:UserId:' . $userid, 480, $token);   //TODO
            return ['status'=>'success', 'data'=>$token];
        }
        return ['status'=>'failed','message'=>'没有用户信息！'];
    }

    static function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];
        }

        return $str;
    }
    //通过token获取用户id
    public static function tokenGetUserId($token) {
        if(Redis::ttl('ApiToken:'.$token)<2505600)
        //if(Redis::ttl('ApiToken:'.$token)<2591880)   //TODO
        {
            return false;
        }
        return Redis::get('ApiToken:'.$token);
    }
    //刷新token
    public static function refreshToken($token) {
        $userid=Redis::get('ApiToken:'.$token);
        if($userid) {
            Redis::del('ApiToken:'.$token);
            $token = self::getRandChar(128);
            if(Redis::get('ApiToken:'.$token)) {
                $token = self::getRandChar(128);
            }
            Redis::setex('ApiToken:'.$token,2592000,$userid);
            Redis::setex('ApiToken:UserId:'.$userid,2592000,$token);
            //Redis::setex('ApiToken:' . $token, 480, $userid);    //TODO
            //Redis::setex('ApiToken:UserId:' . $userid, 480, $token);   //TODO
            return $token;
        }
        return false;
    }
    //用户登出
    public static function apiLogout($token)
    {
        $userid=Redis::get('ApiToken:'.$token);
        Redis::del('ApiToken:'.$token);
        Redis::del('ApiToken:UserId:'.$userid);
        return true;
    }
}